<?php
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

declare (strict_types = 1);

namespace app\wework\controller\user\qr;
use think\facade\Db;
use app\wework\controller\Base;
use app\wework\model\BaseModel;
use app\wework\model\user\qr\QrModel;
use app\wework\model\QyWechatApi;
use think\facade\Session;

include "../extend/PHPExcel/php-excel.class.php";
class Qr extends Base
{
   /**
   * 获取渠道活码分组
   * @return 
   */
   public function group(){
      $data = QrModel::group();
      return success('渠道活码分组',$data);
   }
     public function downexcel(){
          $wid = $this->req->get('wid');
          $id = $this->req->get('id');
          $page = $this->req->get('page',1);
          $size = $this->req->get('size',10);
          $res = QrModel::listById($id,$page,$size,$wid);
          $arr = [
               0 => ['渠道码名称', '分组名称','创建时间', '今日添加客户数（人）','今日流失客户数（人）',"总添加客户数（人）","总流失客户数（人）"]
          ];
          $i = 1;
          foreach($res as $value){
               $arr[$i]["渠道码名称"] = $value["name"];
               $arr[$i]["分组名称"] = $value["groupname"];
               $arr[$i]["创建时间"] = $value["create_time"];
               $arr[$i]["今日添加客户数（人）"] = $value["today_add_number"];
               $arr[$i]["今日流失客户数（人）"] = $value["today_lossing_number"];
               $arr[$i]["总添加客户数（人）"] = $value["total_add_number"];
               $arr[$i]["总流失客户数（人）"] = $value["total_lossing_number"];
               $i++;
          }
          $str = "渠道活码数据统计-列表数据";
          $xls = new \Excel_XML('utf-8', false, '数据导出');
          $xls->addArray($arr);
          $xls->generateXML($str.date('Y-m-d H:i:s'),time());
          exit();
     }

     public function downexcelTable(){
          $wid = $this->req->get('wid');
          $id = $this->req->get('id');
          if(!$id) return error('参数错误');
          $id = explode(",",$id);
          $type = $this->req->get('type');
          $date_type = $this->req->get('date_type',"week");
          $startime = $this->req->get('startime');
          $endtime = $this->req->get('endtime');
          $staff_id = $this->req->get('staff_id');
          if($staff_id)$staff_id = explode(",",$staff_id);
          $date = QrModel::getStatisticsDate($date_type,$startime,$endtime);
          $res = QrModel::statisticsTable($id,$type,$date,$staff_id,$wid);
          if($type == "date"){
               $arr = [
                    0 => ['日期', '客户总数','新增客户数', '流失客户数']
               ];
               $i = 1;
               foreach($res as $value){
                    $arr[$i]["日期"] = $value["date"];
                    $arr[$i]["客户总数"] = $value["total_number"];
                    $arr[$i]["新增客户数"] = $value["new_number"];
                    $arr[$i]["流失客户数"] = $value["lossing_number"];
                    $i++;
               }
          }else if($type == "staff"){
               $arr = [
                    0 => ['员工名称', '客户总数','新增客户数', '流失客户数']
               ];
               $i = 1;
               foreach($res as $value){
                    $arr[$i]["员工名称"] = $value["name"];
                    $arr[$i]["客户总数"] = $value["total_number"];
                    $arr[$i]["新增客户数"] = $value["new_number"];
                    $arr[$i]["流失客户数"] = $value["lossing_number"];
                    $i++;
               }
          }
          
          
          $str = "渠道活码数据统计-表格数据";
          $xls = new \Excel_XML('utf-8', false, '数据导出');
          $xls->addArray($arr);
          $xls->generateXML($str.date('Y-m-d H:i:s'),time());
          exit();
     }

     
    /**
   * 添加|修改 渠道活码分组
   * @param groupid 分组id, 不填则为添加
   * @param name 分组名
   * @return 
   */
   public function groupSave(){
      $wid = Session::get('wid');
      $data = [];
      if($this->req->post('id/d')){
        $data['id']=$this->req->post('id/d');
      }else{
        $data['wid'] = $wid;
        $data['create_time'] = date("Y-m-d H:i:s");
      }
      $data['update_time'] = date("Y-m-d H:i:s");
      $name = $this->req->post('name');
      if(!$name) return error('请填写分组名');
      $group = BaseModel::find('kt_wework_qrgroup',['wid'=>$wid,'name'=>$name]);
      if($group) return error('分组名称已存在');
      $data['name'] = $name;
      $res = BaseModel::save('kt_wework_qrgroup',$data);
      return success('操作成功');
   }
   /**
   * 删除渠道活码分组
   * @param groupid 分组id
   * @return 
   */
   public function groupDelete(){
      $wid = Session::get('wid');
      $groupid = $this->req->post('groupid/d');
      if(!$groupid) return error('请选择分组');
      $qrList = BaseModel::getAll('kt_wework_qr',['wid'=>$wid,'groupid'=>$groupid]);
      if($qrList) return error('请先移除此分组下的渠道活码');
      $res = BaseModel::deleteById('kt_wework_qrgroup',$groupid);
      return success('删除渠道活码分组成功');
   }
   /**
   * 渠道活码列表
   * @param page 页码
   * @param size 每页条数
   * @param groupid 分组id
   * @param name 渠道活码名称
   * @return 
   */
    public function index(){
          $data = [];
          $page = $this->req->post('page',1);
          $size = $this->req->post('size',10);
          $where = [];
          $groupid = $this->req->post('groupid',0);
          if($groupid) $where["groupid"] = $groupid;
           
      $data = QrModel::list($where,$page,$size);
      return success('渠道活码列表',$data);
    }

    public function infos(){
        $data = QrModel::infos();
        
        return success('渠道活码列表',$data);
    }


    /**
   * 更新 | 添加 渠道活码
   * @param id 主键id int 不填则为新增
   * @return 
   */
    public function add()
    {
      $wid = Session::get('wid');
      $data = ['wid'=>$wid];
      $jsonFiled = ['staffid','staff_data','staff_standby','staffup_data','tag','welcome_other_data','dayparting_data','skipverify_time','welcom_shield'];
      $id = $this->req->post('id');  //渠道活码id 有则更新,无则
      if($id) $data['id'] = $id;
      $data['name'] = $this->req->post('name');  //渠道活码id 有则更新,无则
      if(!$data['name']) return error('请输入渠道码名称');
      $data['groupid'] = $this->req->post('groupid');  //渠道活码id 有则更新,无则
      if(!$data['groupid']) return error('请选择分组');
      $data['staff_type'] = $this->req->post('staff_type',1);
      $data['staffid'] = $this->req->post('staffid');  //成员id 数组格式
      $data['staff_standby'] = $this->req->post('staff_standby/a',[]);  //备用成员id 数组格式
      $data['staff_data'] = $this->req->post('staff_data/a');
      if(!$data['staffid'] && $data["staff_type"] == 1) return  error('未选择成员');
      if($data['staff_type'] == 2){
          if(!$data['staff_data']) return error('请添加工作周期');
          if(!$data['staff_standby']) return error('请选择备用员工');
      }
      $data['staffup_status'] = $this->req->post('staffup_status',0);  //员工添加上限是否开启 1:开启 0:关闭
      $data['staffup_data'] = $this->req->post('staffup_data',[]); //员工添加上限数据[{'staffid': 1,'sx':100}]
      $data['staffline_status'] = $this->req->post('staffline_status',0);  //允许员工上下线1:开启 0:关闭  (开启后员工可在侧边栏开启)
      $data['tag_status'] = $this->req->post('tag_status',0);
      $data['tag'] = $this->req->post('tag/a',[]);
      if($data['tag_status']==1&&!$data['tag']) return error('请选择标签');
      $data['customerbz_status'] = $this->req->post('customerbz_status',0);
      $data['customerbzqh_status'] = $this->req->post('customerbzqh_status',1);
      $data['customerbz'] =  $this->req->post('customerbz');
      if($data['customerbz_status']==1 && !$data['customerbz'])  return error('备注不能为空'); //对接口修改客户备注
      $data['customerdes_status'] = $this->req->post('customerdes_status',0); //描述
      $data['customerdes'] = $this->req->post('customerdes');
      if($data['customerdes_status']==1 && !$data['customerdes'])  return error('描述不能为空'); 
      $data['welcome_type'] = $this->req->post('welcome_type',1);  //欢迎语
      $data['welcome_content'] = $this->req->post('welcome_content');  //欢迎语文本内容
      $data['welcome_other_data'] = $this->req->post('welcome_other_data/a',[]);  //欢迎语附件
      if(count($data['welcome_other_data']) > 9)  return error('欢迎语最多添加9个附件');
      $data['dayparting_status'] = $this->req->post('dayparting_status',0);
      $data['dayparting_data'] = $this->req->post('dayparting_data/a',[]);  //欢迎语附件
      $data['welcome_shield_status'] = $this->req->post('welcome_shield_status',0);
      $data['welcom_shield'] = $this->req->post('welcom_shield/a',[]);
      $data['skipverify_status'] = $this->req->post('skipverify_status',0);
      $data['skipverify_type'] = $this->req->post('skipverify_type',1);
      $data['skipverify_time'] = $this->req->post('skipverify_time/a',[]);
      $data['image'] = $this->req->post('image');
      if($data['skipverify_status'] == 1 && $data['skipverify_type'] == 2){
        if(!isset($data['skipverify_time'][0]) || !$data['skipverify_time'][0]) return error('请选择开始时间');
        if(!isset($data['skipverify_time'][1]) || !$data['skipverify_time'][1]) return error('请选择结束时间');
      }
      return QrModel::save($data,$jsonFiled,$this->req->domain());
    }

    /**
   * 渠道活码列表
   * @param id 主键id
   * @return 
   */
    public function detail()
    {
        $wid = Session::get('wid');
        $id = $this->req->get('id');
        if(!$id) return error('参数错误');
        $jsonFiled = ['staffid','staff_data','staff_standby','staffup_data','tag','welcome_other_data','dayparting_data','skipverify_time','welcom_shield',"image"];
        $detail = BaseModel::find('kt_wework_qr',['id'=>$id],true,$jsonFiled);
        $detail["tag_info"] = QrModel::tags($detail["tag"]);
        $detail['staffName'] = BaseModel::column('kt_wework_staff',['id'=>$detail['staffid']],'id,name,avatar');
        $detail['staff_standby_name'] = [];
        if($detail['staff_standby']) $detail['staff_standby_name'] = BaseModel::column('kt_wework_staff',['id'=>$detail['staff_standby']],'id,name,avatar');
        if($detail['staff_data']){
          foreach ($detail['staff_data'] as &$v) {
            $v['staffname'] = [];
            if($v['staffid']) $v['staffname'] = BaseModel::column('kt_wework_staff',['id'=>$v['staffid']],'id,name,avatar');
          }
        }
        
        return success('渠道活码详情',$detail);
    }
    /**
   * 删除渠道活码
   * @param id 主键id
   * @return 
   */
    public function delete()
    {
      $wid = Session::get('wid');
      $id = $this->req->post('id/d');
      if(!$id) return error('参数错误');
      $qr = BaseModel::find('kt_wework_qr',['id'=>$id]);
      $apiRes = QyWechatApi::delContactWay($qr['config_id']);
      if($apiRes['errcode'] != 0 ) return error('删除失败');
      $res = BaseModel::deleteById('kt_wework_qr',$id);
      if($res) return success('删除渠道活码成功');
      return error('删除渠道活码失败');
    }

    /**
   * 统计渠道活码分组弹框
   * @param id 主键id array 
   * @return 
   */
    public function popGroup(){
      $wid = Session::get('wid');
      $data = QrModel::popGroup();
      return success('渠道活码分组弹框',$data);
    }

    /**
   * 活码统计数据渠道列表
   * @param id 主键id array | int
   * @return 
   */
    public function statisticsQrList()
    {
      $wid = Session::get('wid');
      $id = $this->req->post('id');
      $page = $this->req->post('page',1);
      $size = $this->req->post('size',10);
      $res = QrModel::listById($id,$page,$size);
      return success('活码统计数据渠道列表',$res);
    }
     /**
   * 活码统计数据 人数统计
   * @param id 主键id array | int
   * @return 
   */
    public function statisticsInfo()
    {
      $wid = Session::get('wid');
      $id = $this->req->post('id');
      $res = QrModel::statisticsInfo($id);

      return success('活码统计数据',$res);
    }

    /**
   * 活码统计数据 人数统计
   * @param id 主键id array | int
   * @return 
   */
    public function statisticsChartData()
    {
      // var_dump(time());
      // var_dump(Db::table('kt_wework_customer')->whereDay('createtime','2022-07-14')->select());die;
      $wid = Session::get('wid');
      $id = $this->req->post('id');
      $type = $this->req->post('type');
      $date_type = $this->req->post('date_type',"week");
      $startime = $this->req->post('startime');
      $endtime = $this->req->post('endtime');
      $staff_id = $this->req->post('staff_id');
      $date = QrModel::getStatisticsDate($date_type,$startime,$endtime);
      $res = QrModel::statisticsChar($id,$type,$date,$staff_id);

      return success('活码统计数据',$res);
    }

    /**
   * 活码统计数据 人数统计
   * @param id 渠道活码主键id array | int
   * @return 
   */
    public function statisticsTableData()
    {
      // var_dump(time());
      // var_dump(Db::table('kt_wework_customer')->whereTime('createtime','<','2022-07-14')->count());die;
      $wid = Session::get('wid');
      $id = $this->req->post('id');
      $type = $this->req->post('type');
      $date_type = $this->req->post('date_type',"week");
      $startime = $this->req->post('startime');
      $endtime = $this->req->post('endtime');
      $staff_id = $this->req->post('staff_id');
      $date = QrModel::getStatisticsDate($date_type,$startime,$endtime);
      $res = QrModel::statisticsTable($id,$type,$date,$staff_id);

      return success('活码统计数据',$res);
    }
      /**
   * 活码统计数据 人数统计
   * @param id 渠道活码主键id array | int
   * @return 
   */
    public function statisticsStaff()
    {
      // var_dump(time());
      // var_dump(Db::table('kt_wework_customer')->whereTime('createtime','<','2022-07-14')->count());die;
      $wid = Session::get('wid');
      $id = $this->req->post('id');
      $res = QrModel::statisticsStaff($id);
      return success('活码统计数据成员选择',$res);
    }

}
